package com.yunxiao.cloud.common.serializer;

import com.yunxiao.cloud.common.property.RedisKeyPrefixProperties;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description: PrefixStringKeySerializer
 * 对字符串序列化新增前缀
 * @author: lintiangang
 * @date: 2020/8/24 8:57
 * @version: V1.0
 **/
public class PrefixStringKeySerializer extends StringRedisSerializer {

    private Charset charset = StandardCharsets.UTF_8;
    private RedisKeyPrefixProperties prefix;

    public PrefixStringKeySerializer(RedisKeyPrefixProperties prefix) {
        super();
        this.prefix = prefix;
    }

    @Override
    public String deserialize(byte[] bytes) {
        String saveKey = new String(bytes, charset);
        if (prefix.getEnable() != null && prefix.getEnable()){
            String prefixKey = spliceKey(prefix.getKey());
            int indexOf = saveKey.indexOf(prefixKey);
            if (indexOf > 0) {
                saveKey = saveKey.substring(indexOf);
            }
        }

        return saveKey;
    }

    private String spliceKey(String prefixKey) {
        if (!StringUtils.isEmpty(prefixKey) && prefixKey.endsWith(":")) {
            prefixKey = prefixKey + "::";
        }
        return prefixKey;
    }
}
